#include "tcp_client.h"

MyTcpClient::MyTcpClient(const InetAddress& serverAddr) : TcpClient(serverAddr, "tcp_client") {
    setConnectionCallback(std::bind(&MyTcpClient::ConnectCallBack, this, _1));
    setMessageCallback(std::bind(&MyTcpClient::MessageCallBack, this, _1, _2, _3));
}

void MyTcpClient::ConnectCallBack(const TcpConnectionPtr &conn) {
    if (conn->connected()) {
        LOG_INFO << " new connect connected";
        is_alive_ = true;
        OnConnect();
        //todo 此处可以添加连接成功的回调
    } else {
        getLoop()->quit();
        is_alive_ = false;
        OnConnectClose();
    }
}

void MyTcpClient::MessageCallBack(const TcpConnectionPtr& ptr,
                     Buffer* buf,
                     Timestamp) {
    // todo 此处处理接受消息
    int32_t processed = OnMessage(std::string(buf->peek()));
    if (processed < 0) {
        buf->retrieveAll();
        return;
    } else if (processed > 0) {
        buf->retrieve(processed);
    }
}
void MyTcpClient::Send(const std::string &msg) {
    auto conn = TcpClient::connection();
    if (conn) {
        TcpClient::connection()->send(msg);
    }
}
void MyTcpClient::Send(const char *buf, int len) {
    auto conn = TcpClient::connection();
    if (conn) {
        TcpClient::connection()->send(buf, len);
    }
}